<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;



use app\common\model\AppAccountLog;
use app\common\model\BetsLog;
use app\common\model\BonusLog;
use app\common\model\CompanyAccount;
use app\common\model\CompanyAccountLog;
use app\common\model\GamblerKing;
use app\common\model\GamblerKingInvestmentUser;
use app\common\model\GamesLog;
use app\common\model\InvestmentBonusLog;
use app\common\model\KingCategory;
use app\common\model\LotteryResult;
use app\common\model\Member;
use app\common\model\Transfer;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserKingInvestment;
use app\common\model\UserLevel;
use app\common\model\UserNotice;
use think\Db;

/**
 * 用户接口逻辑
 */
class King extends ApiBase
{
    

    
    /**
     *赌王心血公式列表
     */
    public function king_investment_list($data = [])
    {


        $where= ['a.state'=>['in',[1,2,3]],'c.status'=>1];
        $order = 'a.create_time desc';
        if(!empty($data['popularity'])){
            if(!empty($data['sort'])){
               $order = 'c.sort desc';
            }else{
                $order = 'c.sort asc';
            }
        }
        if(!empty($data['bonus'])){
            if(!empty($data['sort'])){
                $order = 'c.user_bonus desc';
            }else{
                $order = 'c.user_bonus asc';
            }
        }
        !empty($data['king_id']) && $where['king_id']=$data['king_id'];
        $list=$this->modelGamblerKingInvestmentUser->alias('a')->field('a.*,c.user_bonus,c.king_bonus,c.winning_rate,c.superior_money,c.stop_loss_rate,c.bonus,c.cycle,c.start_time,c.start_game_time,c.name')->join('__GAMBLER_KING_INVESTMENT__ c','c.id=a.investment_id')->where($where)->order($order)->select();

        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->investment->image;
            $list[$k]['back_image']=$v->investment->back_image;
            $list[$k]['king_name']=$v->king->name;
            $list[$k]['new_rank']=$k+1;
            $list[$k]['start_expire_time']=0;
            if($v['state']==2){
                $list[$k]['start_expire_time']=$v['start_game_time']-TIME_NOW+$v->investment->cycle*3600;
            }elseif ($v['state']==3){
                $list[$k]['start_expire_time']=$v->getData('settlement_time')-TIME_NOW;
            }
            $list[$k]['bnous']=$v->investment->bonus;
           switch ($v['state']){
               case 1:
                   $list[$k]['down_time']=$v->expire_time-TIME_NOW;
                   break;
               case 2:
               case 3:
                   $list[$k]['down_time']=$v->settlement_time-TIME_NOW;
                   break;
           }
            $list[$k]['cycle']=$v->cycle+$v->start_game_time;
            $list[$k]['stop_loss_rate']=$v->investment->stop_loss_rate;
            $list[$k]['superior_money']=$v->investment->superior_money;
            unset($v->investment);
            unset($v->king);
        }

        if(!empty($data['ranking'])){
            $arr1=array_column($list,'new_rank');
            if(!empty($data['sort'])){

                array_multisort($arr1,SORT_DESC,$list);
            }else{
                array_multisort($arr1,SORT_ASC,$list);

            }

        }

        $page=empty($data['page'])?1:$data['page'];
        $pagesize= empty($data['list_rows'])?10:$data['list_rows'];
        $count = count($list);//总条数
        $start=($page-1)*$pagesize;//偏移量，当前页-1乘以每页显示条数
        $list = array_slice($list,$start,$pagesize);
        return ['total'=>$count,'per_page'=>$pagesize,'current_page'=>$page,'last_page'=>ceil($count/$pagesize),'data'=>$list];
//       return ['alltotal'=>$alltotal,'list'=>$list];


    }

    /***
     * 赌王投资top5
     */

    public function investment_top($data){

        $ids=UserAccountLog::where(['investment_type'=>$data['type']])->group('user_id')->column('user_id');
        $count=count($ids);
        $date=date('Y-m-d');
        $start_time=strtotime($date.' 00:00:00');
        $end_time=strtotime($date.' 00:00:00');
        $where['create_time']=['between',[$start_time,$end_time]];
        $where['investment_type']=$data['type'];
        $list=Member::field('id,username')->where(['id'=>['in',$ids]])->select();

        if($count<5){
            $count1=5-$count;;
            if($count!=0){
                $list1=Member::field('id,username')->where(['is_inside'=>0,'id'=>['not in',$ids]])->limit($count1)->select();
                $list=array_merge($list,$list1);

            }else{

                $list1=Member::field('id,username')->where(['is_inside'=>0])->limit($count1)->select();

                $list=$list1;

            }



        }

        foreach ($list as $k=>$v){
            $list[$k]['profit']=$v->getprofit($where);
        }
        $arr1=array_column($list,'profit');
        array_multisort($arr1,SORT_DESC,$list);
        return $list;
    }






    /***
     * 赌王详情
     */

    public function king_detail($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        
        $info=$this->modelGamblerKing->getInfo(['id'=>$data['id']]);
        $king_name = Db::name("gambler_king")->where(["id"=>$data['id']])->find()['name'];
        if(!$info){
            return  ajaxreturn(1,lang('参数错误'));
        }

        $info['image']=$info->image;
        $info['profit']=$info->get_profit_bet(['entrust_count'=>0]);
        $info['tags_name']=$info->tags_name;
        $info['history_number']=$info->history_number;
        $info['max_history_number']=get_max_number($info->history_number);
        $info['fans_profit']=BonusLog::where(['king_id'=>$info['id'],'type'=>2,'number'=>['gt',0]])->sum('number')+0;
        $info['max_fans_profit']=get_max_number($info->fans_profit);
        $info['success_bet_number']=BetsLog::where(['king_id'=>$info['id']])->count();
        $info['max_success_bet_number']=get_max_number($info['success_bet_number']);
        $info['success_number']=BonusLog::where(['king_id'=>$info['id'],'type'=>1,'number'=>['gt',0]])->count();
        $info['max_success_number']=get_max_number($info['success_number']);
        $info['investment_count']=$info->investment_count;
        $info['max_investment_count']=get_max_number($info['investment_count']);
        $info['bets_count']=$info->bets_count;
        $info['max_bets_count']=get_max_number($info['bets_count']);
        $info['max_stop_winn_count']=get_max_number($info['stop_winn_count']);
        $info['max_stop_lose_count']=get_max_number($info['stop_lose_count']);
        $info['max_profit']=get_max_number($info['profit']);
        $info['max_total_money']=get_max_number($info['total_money']);
        $info['max_total_bonus']=get_max_number($info['total_bonus']);

        //假数据统计
        $fake_data = Db::name("fake_data")->where(["king"=>$king_name])->select();
        $fake_info = [];
        $fake_info['history_number'] = 0;
        $fake_info['total_bonus'] = 0;
        $fake_info['total_money'] = 0;
        $fake_info['fans_profit'] = 0;
        $fake_info['bets_count'] = 0;
        foreach($fake_data as $ke1=>$va1){
            $user_arr = explode(',',$va1['user_name']);
            foreach($user_arr as $ke2=>$va2){
                $fake_info['history_number']++;
                $product = Db::name("gambler_king_investment")->where(["id"=>$va1['product_id']])->find();
                $fake_info['total_bonus']+=$va1['money']*$product['king_bonus']/100;
                $fake_info['total_money'] += $va1['money'];
                $fake_info['fans_profit'] += $va1['money']*$va1['percent']/100;
                $fake_info['bets_count'] = $va1['win_count']+$va1['loss_count']+$va1['draw_count'];
            }
        }
        $info['new_history_number']=$info['history_number']+$fake_info['history_number'];
        $info['total_bonus']+=$fake_info['total_bonus'];
        $info['fans_profit']+=$fake_info['fans_profit'];
        $info['new_total_money']=$info['total_money']+$fake_info['total_money'];
        $info['new_bets_count']=$info['bets_count']+$fake_info['bets_count'];
        
        $pay_list=$this->modelUserKingInvestment->field('id,investment_id,user_investment_id,create_time')->where(['user_id'=>$uid,'king_id'=>$data['id'],'state'=>0])->order('state asc')->select();
        
        $pay_ids=[];
        foreach ($pay_list as $k=>$v){
            $pay_list[$k]['name']=$v->investment->data['name'];
            $pay_list[$k]['pirce']=$v->investment->price;
            $pay_list[$k]['image']=$v->investment->image;
            $pay_list[$k]['back_image']=$v->investment->back_image;
            $pay_list[$k]['winning_rate']=$v->investment->winning_rate;
            $pay_list[$k]['stop_loss_rate']=$v->investment->stop_loss_rate;
            $pay_list[$k]['bonus']=$v->investment->bonus;
            $pay_list[$k]['user_bonus']=$v->investment->user_bonus;
            $pay_list[$k]['king_bonus']=$v->investment->king_bonus;
            $pay_list[$k]['cycle']=$v->investment->cycle;
            $pay_list[$k]['profit_probability']=10;  //盈利率
            $pay_list[$k]['total_money']=$v->kinguser->total_money;
            $pay_ids[]=$v['user_investment_id'];
            unset($v->kinguser);
            unset($v->investment);
        }


        $info['has_pay']=$pay_list;
        $where['status']=1;
        $where['state']=['neq',2];
        $where['king_id']=$data['id'];
        if(!empty($pay_ids)){
            $where['id']=['not in',$pay_ids];

        }
        return $info;
    }


    /****
     * 计算相似方案
     */

    public function  king_like_list($data){
        $where['total']=['gt',$data['number']];
        $list=$this->modelGamblerKingInvestment->field('name,id,bonus,king_id')->where($where)->select();
        if(count($list)==0){
            $where['total']=['lt',$data['number']];
            $list=$this->modelGamblerKingInvestment->field('name,id,bonus,king_id')->where($where)->order('total desc')->limit(4)->select();
        }
        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->king->image;
            unset($v->king);
        }
        return $list;

    }





    /****
     * 批量委托赌王产品
     */

    public function buy_investment_more($data){
        $member=$this->logicApiBase->member;
        if($member->level_id==1){
            return  ajaxreturn(1,lang('请先激活会员'));
        }
        if( $this->logicApiBase->member->lei_money> getConfig('max_pei_money')*10000){
            return  ajaxreturn(1,lang('您配置额已达最大上限'));
        }
//        //验证支付密码
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }

        //  $bonus=getConfig('financial_bonus');
        $list=$this->modelUserKingInvestment->where(['id'=>['in',$data['ids']]])->select();
        $total=$this->modelUserKingInvestment->where(['id'=>['in',$data['ids']]])->sum('money')+0;
        if(!$list){
            return  ajaxreturn(1,lang('订单不存在'));
        }
//        if($info['state']!=1){
//            return  ajaxreturn(1,lang('产品没开放'));
//        }
        Db::startTrans();

        $user_account=UserAccount::check(['user_id'=>$this->logicApiBase->member['id'],'wallet_id'=>3],false);


//        $total=$info['price'];

        //扣除金额
        if($total>$user_account['balance']){
            return ajaxreturn(1,lang('理财包余额不足'));
        }

        try{
            foreach ($list as $k=>$info){

                if($info->getData('create_time')+1800<TIME_NOW){
                    Db::rollback();
                    return ajaxreturn(1,lang('已超出付款时间'));
                }
                if($info->kinguser['total_money']>= $info->kinguser->max_money){
                    Db::rollback();
                    return  ajaxreturn(1,lang('该产品众筹金额已达到上限'));
                }
                if($count=UserKingInvestment::where(['user_id'=>$this->logicApiBase->member['id'],'state'=>0,'user_investment_id'=>$info['id']])->count()>0){
                    Db::rollback();
                    return  ajaxreturn(1,lang('您已委托过一次，不能重复付款'));
                }
                $user_account->balance-=$info['money'];
                $user_account->freeze_balance+=$info['money'];

                //写入资金流水
                UserAccountLog::create([
                    'user_id'=>$user_account['user_id'],
                    'number'=>$info['money'],
                    'wallet_id'=>$user_account['wallet_id'],
                    'before_blance'=>$user_account->balance+$info['money'],
                    'after_blance'=>$user_account->balance,
                    'is_add'=>2,
                    'remark'=> '委托理财产品',
                    'type'=>6
                ]);
                //修改赌王产品委托总金额

                $info->kinguser->total_money+=$info['money'];
                $info->kinguser->surplus_money+=$info['money'];
                $info->kinguser->stop_win_money= $info->kinguser->surplus_money*$info->investment['winning_rate']/100;
                $info->kinguser->king_win_account+=$info['balance'];
                $info->kinguser->stop_lose_account+=$info['balance_lock'];
                $info->kinguser->save();
                $info->king->surplus_total_money+=$info['money'];
                $info->king->total_money+=$info['money'];
                $info->king->save();
                $info->state=0;
                $info->save();
                //写入消息通知

                $user_account->member->is_new=1;
                $user_account->member->save();
                //增加业绩
                $user_account->member->upgrade($info['money'],[]);

                user_notice( $info['user_id'], '恭喜您成功委托给（'.$info->king->data['name'].'），您选择的委托产品是'.($info->investment->cycle+$info->investment->start_game_time).'天后分红到账，在这个过程中您静候交易员的动态，分红到账后可随时提现，如您本次委托的交易员您满意，可进行二次委托，点击已完成订单的详情页面可快捷的完成再次委托');
                user_notice( $info->kinguser['user_id'], '您的总筹产品'.$info->investment->data['name'].',在'.date('Y-m-d H:i:s').'时间由会员账号'.$info->member->username.'完成委托，每一次的委托来源您的付出和你的专业能力，恭喜您！！');
            }
            $user_account->save();

            Db::commit();
            return ajaxreturn(0,lang('购买成功'));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }







    }

    //创建订单
    public function  create_king_order($data){
//        if( $this->logicApiBase->member->lei_money> getConfig('max_pei_money')*10000){
//            return  ajaxreturn(1,lang('您配置额已达最大上限'));
//        }
//
        $member=$this->logicApiBase->member;
        if($member->level_id==1){
            return  ajaxreturn(1,lang('请先激活会员'));
        }
        $ids=explode(',',$data['ids']);
        $list=$this->modelGamblerKingInvestmentUser->where(['id'=>['in',$ids]])->select();

        if(!$list){
            return  ajaxreturn(1,lang('产品不存在'));
        }
        try{
            $ids=[];


            foreach ($list as $k=>$info){
                if($info['user_id']== $this->logicApiBase->member['id']){
                    Db::rollback();
                    return  ajaxreturn(1,lang('不能委托自己得产品'));
                }
                if($count=UserKingInvestment::where(['user_id'=>$this->logicApiBase->member['id'],'state'=>0,'user_investment_id'=>$info['id']])->count()>0){
                    Db::rollback();
                    return  ajaxreturn(1,lang('您已委托过一次，不能重复委托'));
                }
                if($info['total_money']>= $info->max_money){
                    Db::rollback();
                    return  ajaxreturn(1,lang('该产品众筹金额已达到上限'));
                }
                $stop_lose_account=$info['price']*$info->investment->stop_loss_rate/100;
                $id=UserKingInvestment::create([
                    'user_id'=>$this->logicApiBase->member['id'],
                    'investment_id'=>$info['investment_id'],
                    'user_investment_id'=>$info['id'],
                    'king_id'=>$info->king_id,
                    'money'=>$info['price'],
                    'state'=>1,
                    'balance'=>$stop_lose_account,
                    'balance_lock'=>$info['price']-$stop_lose_account,
                    'expire_time'=>$info['settlement_time'],
                ]);
                $ids[]=$id->id;

            }
            Db::commit();
            return implode(',',$ids);
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }


    //创建订单
    public function  create_king_order_again($data){
//        if( $this->logicApiBase->member->lei_money> getConfig('max_pei_money')*10000){
//            return  ajaxreturn(1,lang('您配置额已达最大上限'));
//        }
//
        $member=$this->logicApiBase->member;
        if($member->level_id==1){
            return  ajaxreturn(1,lang('请先激活会员'));
        }
        $info=$this->modelUserKingInvestment->where(['id'=>$data['id']])->find();
        if(!$info){
            return  ajaxreturn(1,lang('订单不存在'));
        }
        $king_investment=$this->modelGamblerKingInvestmentUser->where(['investment_id'=>$info['investment_id'],'king_id'=>$info['king_id'],'state'=>1])->find();
        if(!$king_investment){
            return  ajaxreturn(1,lang('该产品已关闭'));
        }
        if($count=UserKingInvestment::where(['user_id'=>$this->logicApiBase->member['id'],'state'=>0,'user_investment_id'=>$info['investment_id']])->count()>0){
            return  ajaxreturn(1,lang('您已委托过一次，不能重复委托'));
        }
        if($king_investment['total_money']>=$king_investment->max_money){
            return  ajaxreturn(1,lang('该产品众筹金额已达到上限'));
        }
        if($king_investment['state']==2){
            return  ajaxreturn(1,lang('该产品公募已结束'));
        }
        if($king_investment['state']==3){
            return  ajaxreturn(1,lang('该产品已经在游戏中'));
        }

        try{


            $user_account=UserAccount::check(['user_id'=>$this->logicApiBase->member['id'],'wallet_id'=>3],false);




            //扣除金额
            if($king_investment['price']>$user_account['balance']){
                return ajaxreturn(1,lang('理财包余额不足'));
            }

            $stop_lose_account=$king_investment['price']*$king_investment->investment->stop_loss_rate/100;
            $id=UserKingInvestment::create([
                'user_id'=>$this->logicApiBase->member['id'],
                'investment_id'=>$king_investment['investment_id'],
                'user_investment_id'=>$king_investment['id'],
                'king_id'=>$king_investment->king_id,
                'money'=>$king_investment['price'],
                'state'=>0,
                'balance'=>$stop_lose_account,
                'balance_lock'=>$king_investment['price']-$stop_lose_account,
                'expire_time'=>$king_investment['settlement_time'],
            ]);

            $user_account->balance-=$info['money'];
            $user_account->freeze_balance+=$info['money'];
            $user_account->save();
            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$user_account['user_id'],
                'number'=>$info['money'],
                'wallet_id'=>$user_account['wallet_id'],
                'before_blance'=>$user_account->balance+$info['money'],
                'after_blance'=>$user_account->balance,
                'is_add'=>2,
                'remark'=> '委托理财产品',
                'type'=>6
            ]);
            //修改赌王产品委托总金额

            $king_investment->total_money+=$info['money'];
            $king_investment->surplus_money+=$info['money'];
            $king_investment->stop_win_money= $info->kinguser->surplus_money*$info->investment['winning_rate']/100;
            $king_investment->king_win_account+=$info['balance'];
            $king_investment->stop_lose_account+=$info['balance_lock'];
            $king_investment->save();
            $info->king->surplus_total_money+=$info['money'];
            $info->king->total_money+=$info['money'];
            $info->king->save();



            $user_account->member->is_new=1;
            //增加业绩

            $user_account->member->save();
            $this->logicApiBase->member->upgrade($info['money'],[]);
            user_notice( $info['user_id'], '恭喜您成功委托给（'.$info->king->data['name'].'），您选择的委托产品是'.($info->investment->cycle+$info->investment->start_game_time).'天后分红到账，在这个过程中您静候交易员的动态，分红到账后可随时提现，如您本次委托的交易员您满意，可进行二次委托，点击已完成订单的详情页面可快捷的完成再次委托');
            user_notice( $info->kinguser['user_id'], '您的总筹产品'.$info->investment->data['name'].',在'.date('Y-m-d H:i:s').'时间由会员账号'.$info->member->username.'完成委托，每一次的委托来源您的付出和你的专业能力，恭喜您！！');

            Db::commit();
            return $id->id;
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }

    /****
     * 赌王撤资列表
     */

    public function out_investment_list($data){

        $member=$this->logicApiBase->member;
        $page=empty($data['page'])?1:$data['page'];
        $pagesize= empty($data['list_rows'])?10:$data['list_rows'];
        $list=$this->modelUserKingInvestment->alias('a')->field('a.*,c.user_bonus,c.king_bonus,c.winning_rate,c. superior_money,c.stop_loss_rate,c.bonus,c.cycle,c.name,u.state as king_state')->join('__GAMBLER_KING_INVESTMENT__ c','c.id=a.investment_id')->join('__GAMBLER_KING_INVESTMENT_USER__ u','u.id=a.user_investment_id')->field('a.*,c.user_bonus,c.king_bonus,c.cycle,c.name')->where(['a.state'=>1,'u.state'=>['in',[1,4]],'a.user_id'=>$member['id']])->limit($pagesize)->page($page)->select();
        $count=$this->modelUserKingInvestment->alias('a')->join('__GAMBLER_KING_INVESTMENT__ c','c.id=a.investment_id')->join('__GAMBLER_KING_INVESTMENT_USER__ u','u.id=a.user_investment_id')->where(['a.state'=>1,'u.state'=>['in',[1,4]],'a.user_id'=>$member['id']])->count();
        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->investment->image;
            $list[$k]['back_image']=$v->investment->back_image;
            $list[$k]['start_time']=date('Y-n-d H:i:s',$v->kinguser->start_time);
            $list[$k]['expire_time']=date('Y-n-d H:i:s',$v->kinguser->expire_time);
            unset($v->kinguser);
            unset($v->investment);
        }
        return ['total'=>$count,'per_page'=>$pagesize,'current_page'=>$page,'last_page'=>ceil($count/$pagesize),'data'=>$list];

    }


    /****
     * 赌王订单列表
     */

    public function user_investment_list($data){
        $member=$this->logicApiBase->member;
        $where=['a.user_id'=>$member['id']];
        if(!empty($data['type'])){
            switch($data['type']){
                case  1:
                    //今日
                    $where['a.create_time']=['between',[getTodayStart(),getTodayEnd()]];

                    break;
                case  2:
                    //昨日
                    $where['a.create_time']=['between',[getTodayStart()-86400,getTodayEnd()-86400]];
                    break;
                case  3:
                    //近七天
                    $where['a.create_time']=['between',[getTodayStart()-86400*7,getTodayEnd()]];
                    break;
                case  4:
                    //近30天
                    $where['a.create_time']=['between',[getTodayStart()-86400*30,getTodayEnd()]];


                    break;


            }
        }

        if(!empty($data['state_type'])){
            switch($data['state_type']){
                case  1:
                    //近7天订单
                    $where['a.state']=['in',[0,5,6,1]];
                    break;
                case  2:
                    //已完成

                    break;
                case  3:

                    break;


            }
        }

        if(!empty($data['start_time']) && !empty($data['end_time'])){

            $where['a.create_time']=['between',[strtotime($data['start_time'].' 00:00:00'),strtotime($data['end_time'].' 23:59:59') ]];
        }

        !empty($data['state']) && $where['a.state']=$data['state'];

        if(isset($data['state']) && $data['state']=='0'){
            $where['a.state']='0';
        }
        $page=empty($data['page'])?1:$data['page'];
        $pagesize= empty($data['list_rows'])?10:$data['list_rows'];
        $list=$this->modelUserKingInvestment->alias('a')->field('a.*,c.user_bonus,c.king_bonus,c.winning_rate,c. superior_money,c.stop_loss_rate,c.cycle,c.name,u.state as king_state')->join('__GAMBLER_KING_INVESTMENT__ c','c.id=a.investment_id')->join('__GAMBLER_KING_INVESTMENT_USER__ u','u.id=a.user_investment_id')->field('a.*,c.user_bonus,c.king_bonus,c.cycle,c.name')->where($where)->order('id desc')->limit($pagesize)->page($page)->select();
        $count=$this->modelUserKingInvestment->alias('a')->join('__GAMBLER_KING_INVESTMENT__ c','c.id=a.investment_id')->join('__GAMBLER_KING_INVESTMENT_USER__ u','u.id=a.user_investment_id')->where($where)->count();

        foreach ($list as $k=>$v){
            $list[$k]['king_name']=$v->king->data['name'];
            $list[$k]['king_image']=$v->member->avtar;
            $list[$k]['image']=$v->investment->image;
            $list[$k]['investment_count']=$v->kinguser->order_count;
            $list[$k]['investment_total']=$v->money;
            $list[$k]['round']=$v->kinguser->round;
            if($v['state']==0 || $v['state']==5){
                $list[$k]['down_time'] = $v->kinguser->start_game_end_int-TIME_NOW;
            }else{
                $list[$k]['down_time'] = $v->kinguser->settlement_time-TIME_NOW;
            }
            $list[$k]['bonus_money']=BonusLog::where(['user_investment_id'=>$v['user_investment_id'],'user_id'=>$v['user_id']])->value('number')+0;

            $list[$k]['back_image']=$v->investment->back_image;
            $list[$k]['start_time']=date('Y-n-d H:i:s',$v->kinguser->start_time);
            $list[$k]['expire_time']=date('Y-n-d H:i:s',$v->kinguser->expire_time);
            unset($v->kinguser);
            unset($v->king);
            unset($v->member);
            unset($v->investment);
        }
        return ['total'=>$count,'per_page'=>$pagesize,'current_page'=>$page,'last_page'=>ceil($count/$pagesize),'data'=>$list];

    }

    /****
     * 赌王撤资
     */

    public function out_investment($data){

//        //验证支付密码
//        if(!$this->logicApiBase->member->check_pin_password($data['token'],$data['pin_password'])){
//            return  ajaxreturn(1,lang('支付密码错误'));
//        }


        Db::startTrans();
        $total=0;
        try{
            if($data['type']==1){
                $user_account=UserAccount::check(['user_id'=>$this->logicApiBase->member['id'],'wallet_id'=>3],false);
                $info=$this->modelUserKingInvestment->where(['id'=>$data['id'],'state'=>0,'user_id'=>$this->logicApiBase->member['id']])->lock(true)->find();
                if(!$info){
                    return ajaxreturn(1,lang('订单不存在'));
                }
                if($info->kinguser->state==3){
                    return ajaxreturn(1,lang('产品已开始,不能解除'));
                }
                $total=$info['money'];

                //修改状态为解除中



                $user_account->balance+=$info['money'];
                $user_account->freeze_balance-=$info['money'];

                //写入资金流水
                UserAccountLog::create([
                    'user_id'=>$user_account['user_id'],
                    'number'=>$info['money'],
                    'wallet_id'=>$user_account['wallet_id'],
                    'before_blance'=>$user_account->balance-$info['money'],
                    'after_blance'=>$user_account->balance,
                    'is_add'=>1,
                    'remark'=>'用户解除',
                    'type'=>8
                ]);

                $user_account->save();
                $info->kinguser->total_money-=$total;
                $info->kinguser->surplus_money-=$total;
                $info->kinguser->stop_win_money= $info->kinguser->surplus_money*$info->investment['winning_rate']/100;
                $info->kinguser->king_win_account-=$info['balance'];
                $info->kinguser->stop_lose_account-=$info['balance_lock'];
                $info->kinguser->save();
                $info->king->total_money-=$total;
                $info->king->surplus_total_money-=$total;
                $info->king->save();
                //减少业绩
//                //等级降级
////                $user_account->member->lei_money-=$total;
////                $user_account->member->save();
////                $user_account->member->downgrade($total);
                //增加业绩
                $this->logicApiBase->member->downgrade($info['money']);
                UserKingInvestment::where(['id'=>$data['id']])->update(['state'=>2,'update_time'=>time()]);
                user_notice( $info['user_id'], '您的委托'.$info->investment->data['name'].'产品,在'.date(' Y-m-d H:i:s').'时间操作取消委托订单，订单已取消成功，如您操作失误可在已完成订单中点击订单进行二次委托。');
                Db::commit();
                return ajaxreturn(0,lang('退款成功'));
            }else{
                $info=$this->modelUserKingInvestment->where(['id'=>$data['id'],'state'=>1,'user_id'=>$this->logicApiBase->member['id']])->lock(true)->find();
                if(!$info){
                    return ajaxreturn(1,lang('订单不存在'));
                }
                $info->state=3;
                $info->update_time=TIME_NOW;
                $info->save();
                Db::commit();
            }

        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }




    }




    /***
     * 购买投资，心血公式列表
     */

    public function  investment_list($data){
        $ids=explode(',',$data['ids']);
        $where=['a.id'=>['in',$ids]];
        $list=$this->modelUserKingInvestment->alias('a')->field('a.*,c.user_bonus,c.king_bonus,c.cycle,c.start_game_time,c.name,c.winning_rate,c.stop_loss_rate,c.superior_money')->join('__GAMBLER_KING_INVESTMENT__ c','c.id=a.investment_id')->where($where)->select();
        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->king->user->avtar;
            $list[$k]['king_name']=$v->king->name;
            unset($v->king);
        }

        return $list;

    }


    //理财详情


    public function investment_detail($data){
        $info=$this->modelUserKingInvestment->getInfo(['id'=>$data['id'],'user_id'=>$this->logicApiBase->member['id']]);

        if(!$info){
            return  ajaxreturn(1,lang('参数错误'));
        }
        $info['investment_count']=$info->kinguser->order_count;
        $info['investment_total']=$info->kinguser->order_total;
        $info['investment_days']=$info->investment->start_game_time;
        $info['king_name']=$info->king->data['name'];
        $info['round']=$info->kinguser->data['round'];
        $info['king_bonus']=$info->investment->king_bonus;
        $info['user_bonus']=$info->investment->user_bonus;
        $info['bonus_money']=BonusLog::where(['user_investment_id'=>$info['user_investment_id'],'user_id'=>$info['user_id']])->value('number');
        $info['investment_name']=$info->investment->data['name'];
        $info['winning_rate']=$info->investment->winning_rate;
        $info['stop_loss_rate']=$info->investment->stop_loss_rate;
        $info['start_time']=date('Y-m-d H:i:s',$info->kinguser->create_time);
        $info['end_time']=date('Y-m-d H:i:s',$info->kinguser->expire_time);
        $info['bonus_time']=date('Y-m-d H:i:s',$info->kinguser->settlement_time);
        $info['cycle'] = $info->investment->start_game_time;
        if($info['state']==0 || $info['state']==5){
            $info['down_time'] = $info->kinguser->start_game_end_int-TIME_NOW;
        }else{
            $info['down_time'] = $info->kinguser->settlement_time-TIME_NOW;
        }
        unset($info->king);
        unset($info->kinguser);
        unset($info->investment);
        return $info;

    }



    /***
     * 历史签约列表
     */

    public function  history_investment($data){
        if(!empty($data['time_type'])){
            switch ($data['time_type']){
                case 1:
                    $date=date('Y-m-d');
                    $start_time=strtotime($date.' 00:00:00');
                    $end_time=strtotime($date.' 23:59:59');
                    $where['create_time']=['between',[$start_time,$end_time]];
                    break;
                case 2:

                    $curr = date("Y-m-d");
                    $w=date('w');//获取当前周的第几天 周日是 0 周一到周六是1-6  
                    $beginLastweek=strtotime("$curr -".($w ? $w-1 : $w-6).' days');//获取本周开始日期，如果$w是0是周日:-6天;其它:-1天   

                    $s=date('Y-m-d 00:00:00',$beginLastweek);

                    $start_time=strtotime($s);
                    $end_time=strtotime(date('Y-m-d 23:59:59',strtotime("$s +6 days")));
                    $where['create_time']=['between',[$start_time,$end_time]];
                    break;
                case 3:
                    $start_time=mktime(0,0,0,date('m'),1,date('Y'));
                    $end_time=mktime(23,59,59,date('m'),date('t'),date('Y'));
                    $where['create_time']=['between',[$start_time,$end_time]];
                    break;
                case 4:

                    break;
            }
        }else{
            if(!empty($data['start_time']) && !empty($data['end_time']) ){
                $start_time=strtotime($data['start_time'].' 00:00:00');
                $end_time=strtotime($data['end_time'].' 23:59:59');
                $where['create_time']=['between',[$start_time,$end_time]];
            }
        }
        $where['state']=['in',[2,3]];



        $list=$this->modelUserKingInvestment->getList($where,'*','id desc');

        foreach ($list as $ke=>$va){
            $list[$ke]['king_name']=$va->king->data['name'];
            $list[$ke]['image']=$va->investment->image;
            if($va['state']==0 || $va['state']==5){
                $list[$ke]['down_time'] = $va->kinguser->start_game_end_int-TIME_NOW;
            }else{
                $list[$ke]['down_time'] = $va->kinguser->settlement_time-TIME_NOW;
            }
            $list[$ke]['investment_name']=$va->investment->data['name'];
            unset($va->investment);
            unset($va->kinguser);
            unset($va->king);
        }


        return $list;
    }



    /***
     * 理财中心首页
     */
    public function  investment_center(){
        $pay_list=$this->modelBonusLog->field('id,investment_id,pei_money,serial_number,king_id,user_investment_id,number,create_time')->where(['user_id'=>$this->logicApiBase->member['id'],'type'=>2])->order('id desc')->select();
        foreach ($pay_list as $k=>$v){
            $pay_list[$k]['name']=$v->investment->data['name'];
            $pay_list[$k]['bonus_count']=1;
            $pay_list[$k]['king_name']=$v->king->data['name'];
            unset($v->investment);
            unset($v->king);
        }
        $time=time();
        $notice= $this->modelUserNotice->field('id,title,create_time')->where(['user_id'=>$this->logicApiBase->member['id'],'type'=>1])->limit(5)->order('id desc')->select();
        foreach ($notice as $k=>$v){

            $minute=floor(($time-$v->data['create_time'])/60);
            $hour=floor($minute/60);
            $day=floor($hour/24);
            $month=floor($day/30);
            if(floor(($time-$v->data['create_time']))<1){
                $notice[$k]['time']=floor(($time-$v->data['create_time'])).lang('秒前');
            }elseif($minute<60){
                $notice[$k]['time']=$minute.lang('分钟前');

            }elseif($hour<24){
                $notice[$k]['time']=$day.lang('小时前');

            }elseif($day<30){
                $notice[$k]['time']=$day.lang('天前');
            }else{

                $notice[$k]['time']=$month.lang('月前');
            }

        }

        return ['pay_list'=>$pay_list,'notice'=>$notice];
    }




    /****
     * 用户分红数据
     */
    public function  user_bonus(){
        $member=$this->logicApiBase->member;
        $count=BonusLog::where(['user_id'=>$member['id'],'type'=>2,'number'=>['gt',0],'is_read'=>0])->count();
        $money=BonusLog::where(['user_id'=>$member['id'],'type'=>2,'number'=>['gt',0],'is_read'=>0])->sum('number')+0;


        return ['count'=>$count,'money'=>$money];


    }











    /****
     * 赌王榜首页
     */
    public function  king_index($data){
        $where=['status'=>1,'state'=>2];
        if(!empty($data['search'])){
            $where['name']=['like','%'.$data['search'].'%'];
        }
        $cate_list=KingCategory::all(['status'=>1,'parent_id'=>0]);
        foreach ($cate_list as $k=>$v){
            $cate_list[$k]['image']=$v->image;
            $where['cates']=['like','%,'.$v['id'].',%'];
            $king_list=GamblerKing::field('id,user_id,name,sex,winning_rate,fail_rate,tags,help_number,cover_id,credit_score')->where($where)->order('profit desc')->select();
            foreach ($king_list as $ke=>$va){
                $king_list[$ke]['image']=$va->image;
                $king_list[$ke]['investment_count']=$va->investment_count;

                $king_list[$ke]['tags_name']=$va->tags_name;

            }
//            $arr1=array_column($king_list,'achievement');
//            array_multisort($arr1,SORT_DESC,$king_list);
            if(count($king_list)>3){
                $king_list=array_slice($king_list,0,3);
            }

            $cate_list[$k]['king_list']=$king_list;
        }

        return $cate_list;

    }

    /**
     * TOP首页
     */
    public function  king_top_index($data){
            $user_list=$king_list=$otc_list=[];
            $where='u.status=1 and u.is_inside=0';

            $sql_user_1="SELECT u.cover_id,u.id,u.username ,SUM(d.money) AS total_money  FROM tp_member AS u LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE type=1) AS d ON u.id=d.user_id  where $where GROUP BY u.id   ORDER BY total_money   DESC  limit 3";
            $sql_user_2="SELECT u.cover_id,u.id,u.username,SUM(d.money) AS total_money  FROM tp_member AS u LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE type=2) AS d ON u.id=d.user_id  where $where GROUP BY u.id   ORDER BY total_money   DESC  limit 3";
            $sql_user_3="SELECT u.cover_id,u.id,u.username,SUM(d.money) AS total_money  FROM tp_member AS u LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE type=3) AS d ON u.id=d.user_id  where $where GROUP BY u.id   ORDER BY total_money   DESC  limit 3";
            $sql_user_4="SELECT u.cover_id,u.id,u.username ,SUM(d.money) AS total_money  FROM tp_member AS u LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE type=4) AS d ON u.id=d.user_id  where $where GROUP BY u.id   ORDER BY total_money   DESC  limit 3";
            $user_list1=Db::query($sql_user_1);
            $user_list2=Db::query($sql_user_2);
            $user_list3=Db::query($sql_user_3);
            $user_list4=Db::query($sql_user_4);

            $king_cate=KingCategory::where(['status'=>1,'parent_id'=>['gt',0]])->column('name','id');

            $where='u.status=1 and u.state=2';

            $sql_king_5="SELECT m.cover_id,u.user_id,u.id,u.name,m.mobile ,u.credit_score,tags,SUM(d.money) AS total_money  FROM tp_gambler_king AS u INNER JOIN tp_member m on u.user_id=m.id LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE type=5) AS d ON u.id=d.king_id  where $where GROUP BY u.id   ORDER BY total_money   DESC limit 3";
            $sql_king_6="SELECT m.cover_id,u.user_id,u.id,u.name,u.credit_score,tags,SUM(d.money) AS total_money  FROM tp_gambler_king AS u INNER JOIN tp_member m on u.user_id=m.id LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE type=5) AS d ON u.id=d.king_id  where $where GROUP BY u.id   ORDER BY total_money   DESC limit 3";
            $sql_king_7="SELECT m.cover_id,u.user_id,u.id,u.name,u.credit_score,tags ,SUM(d.money) AS total_money  FROM tp_gambler_king AS u INNER JOIN tp_member m on u.user_id=m.id LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE type=5) AS d ON u.id=d.king_id  where $where GROUP BY u.id   ORDER BY total_money   DESC limit 3";
            $sql_king_8="SELECT m.cover_id,u.user_id,u.id,u.name,u.credit_score,tags ,SUM(d.money) AS total_money  FROM tp_gambler_king AS u INNER JOIN tp_member m on u.user_id=m.id LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE type=5) AS d ON u.id=d.king_id  where $where GROUP BY u.id   ORDER BY total_money   DESC limit 3";
            $sql_king_9="SELECT m.cover_id,u.user_id,u.id,u.name,u.credit_score,tags,SUM(d.money) AS total_money  FROM tp_gambler_king AS u INNER JOIN tp_member m on u.user_id=m.id LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE type=5) AS d ON u.id=d.king_id  where $where GROUP BY u.id   ORDER BY total_money   DESC limit 3";

            $king_list5=Db::query($sql_king_5);
            $king_list6=Db::query($sql_king_6);
            $king_list7=Db::query($sql_king_7);
            $king_list8=Db::query($sql_king_8);
            $king_list9=Db::query($sql_king_9);
            $where=['state'=>2];

            $shop_list=$this->modelOtcShop->field('id,shop_name,user_id,total_count')->where($where)->order('total_count desc')->limit(3)->select();

            foreach ($user_list1 as $k=>$v){
                $user_list1[$k]['image']=get_picture_url($v['cover_id']);
                $user_list1[$k]['total_money']+=0;
                $user_list1[$k]['credit_score']=100;
                $user_list2[$k]['image']=get_picture_url($v['cover_id']);
                $user_list2[$k]['total_money']+=0;
                $user_list2[$k]['credit_score']=100;
                $user_list3[$k]['image']=get_picture_url($v['cover_id']);
                $user_list3[$k]['total_money']+=0;
                $user_list3[$k]['credit_score']=100;
                $user_list4[$k]['image']=get_picture_url($v['cover_id']);
                $user_list4[$k]['total_money']+=0;
                $user_list4[$k]['credit_score']=100;

                if(!empty($king_list5[$k])){
                    $king_list5[$k]['image']= get_picture_url($king_list5[$k]['cover_id']);
                    $tags=rtrim($king_list5[$k]['tags'], ",");
                    $tags=ltrim($tags, ",");
                    $tags=explode(',',$tags);
                    $tag='';

                    foreach ($tags as $ke=>$va){
                        if(isset($king_cate[$va])){
                            if($ke==0){
                                $tag.=$king_cate[$va];
                            }else{
                                $tag.=','.$king_cate[$va];
                            }
                        }

                    }

                    $king_list5[$k]['tags_name']=$tag;
                    $king_list5[$k]['total_money']+=0;

                }
                if(!empty($king_list6[$k])){
                    $king_list6[$k]['image']= get_picture_url( $king_list6[$k]['cover_id']);
                    $tags=rtrim($king_list5[$k]['tags'], ",");
                    $tags=ltrim($tags, ",");
                    $tags=explode(',',$tags);
                    $tag='';
                    foreach ($tags as $ke=>$va){
                        if(isset($king_cate[$va])){
                            if($ke==0){
                                $tag.=$king_cate[$va];
                            }else{
                                $tag.=','.$king_cate[$va];
                            }
                        }
                    }

                    $king_list6[$k]['tags_name']=$tag;
                    $king_list6[$k]['total_money']+=0;

                }
                if(!empty($king_list7[$k])){
                    $king_list7[$k]['image']= get_picture_url( $king_list7[$k]['cover_id']);
                    $tags=rtrim($king_list5[$k]['tags'], ",");
                    $tags=ltrim($tags, ",");
                    $tags=explode(',',$tags);
                    $tag='';
                    foreach ($tags as $ke=>$va){
                        if(isset($king_cate[$va])){
                            if($ke==0){
                                $tag.=$king_cate[$va];
                            }else{
                                $tag.=','.$king_cate[$va];
                            }
                        }
                    }

                    $king_list7[$k]['tags_name']=$tag;
                    $king_list7[$k]['total_money']+=0;

                }
                if(!empty($king_list8[$k])){
                    $king_list8[$k]['image']=get_picture_url( $king_list8[$k]['cover_id']);
                    $tags=rtrim($king_list5[$k]['tags'], ",");
                    $tags=ltrim($tags, ",");
                    $tags=explode(',',$tags);
                    $tag='';
                    foreach ($tags as $ke=>$va){
                        if(isset($king_cate[$va])){
                            if($ke==0){
                                $tag.=$king_cate[$va];
                            }else{
                                $tag.=','.$king_cate[$va];
                            }
                        }
                    }

                    $king_list8[$k]['tags_name']=$tag;
                    $king_list8[$k]['total_money']+=0;

                }
                if(!empty($king_list9[$k])){
                    $king_list9[$k]['image']= get_picture_url($king_list9[$k]['cover_id']);
                    $tags=rtrim($king_list5[$k]['tags'], ",");
                    $tags=ltrim($tags, ",");
                    $tags=explode(',',$tags);
                    $tag='';
                    foreach ($tags as $ke=>$va){
                        if(isset($king_cate[$va])){
                            if($ke==0){
                                $tag.=$king_cate[$va];
                            }else{
                                $tag.=','.$king_cate[$va];
                            }
                        }
                    }

                    $king_list9[$k]['tags_name']=$tag;
                    $king_list9[$k]['total_money']+=0;
                }
                if(!empty($shop_list[$k])){
                    $shop_list[$k]['image']= $shop_list[$k]->member->avtar;
                    unset($shop_list[$k]->member);
                }




            }
            $user_list[]=['id'=>1,'list'=>$user_list1];
            $user_list[]=['id'=>2,'list'=>$user_list2];
            $user_list[]=['id'=>3,'list'=>$user_list3];
            $user_list[]=['id'=>4,'list'=>$user_list4];

            $king_list[]=['id'=>5,'list'=>$king_list5];
            $king_list[]=['id'=>6,'list'=>$king_list6];
            $king_list[]=['id'=>7,'list'=>$king_list7];
            $king_list[]=['id'=>8,'list'=>$king_list8];
            $king_list[]=['id'=>9,'list'=>$king_list9];
            $otc_list[]=['id'=>10,'list'=>$shop_list];

            $arr=[
              'user_list'=>$user_list,
                'king_list'=>$king_list,
                'otc_list'=>$otc_list
            ];

            return $arr;



    }





    /***
     * 更多赌王
     */

    public function  more_king($data){
        $type=$data['user_type'];
        $where='u.status=1 and u.state=2';
        $where1=' type='.$type;
        $where3=['status'=>1,'state'=>2];
        if (!empty($data['start_time'])) {
            if (!empty($data['end_time'])) {
                $where1.=' and  u.create_time between '.strtotime($data['start_time'] . ' 00:00:00') .' and '.strtotime($data['end_time'] . ' 23:59:59');

            } else {
                $where1.=' and  u.create_time between '.strtotime($data['start_time'] . ' 00:00:00') .' and '.strtotime($data['start_time'] . ' 23:59:59');
            }
        }
        switch ($data['type']){
            case 1:
                //今天
                $date=date('Y-m-d');
                $start_time=strtotime($date.' 00:00:00');
                $end_time=strtotime($date.' 23:59:59');
                $where1.=' and create_time between '.$start_time.' and '.$end_time;
                break;
            case 2:
                //昨天
                $date=date('Y-m-d');
                $start_time=strtotime($date.' 00:00:00')-86400;
                $end_time=strtotime($date.' 23:59:59')-86400;
                $where1.=' and create_time between '.$start_time.' and '.$end_time;
                break;

                break;
            case 3:
                //  前天
                $date=date('Y-m-d');
                $start_time=strtotime($date.' 00:00:00')-86400*2;
                $end_time=strtotime($date.' 23:59:59')-86400*2;
                $where1.=' and create_time between '.$start_time.' and '.$end_time;
                break;


                break;
            case 4:
                //近7天
                $start_time=TIME_NOW-86400*7;
                $end_time=TIME_NOW;
                $where1.=' and create_time between '.$start_time.' and '.$end_time;

                break;
            case 5:

                //近15天
                $start_time=TIME_NOW-86400*15;
                $end_time=TIME_NOW;
                $where1.=' and create_time between '.$start_time.' and '.$end_time;

                break;
            case 6:
//              //近30天
                $start_time=TIME_NOW-86400*30;
                $end_time=TIME_NOW;
                $where1.=' and create_time between '.$start_time.' and '.$end_time;
                break;
        }
        !empty($data['search']) && $where.=' and u.name like "%'.$data['search'].'%"';
        !empty($data['search']) && $where3['username']=['like','%'.$data['search'].'%'];
        // dd($where1);
        $pagesize= empty($data['list_rows'])?10:$data['list_rows'];
        $currPage= empty($data['page'])?1:$data['page'];
        $start=($currPage-1)*$pagesize;
        $sql="SELECT m.cover_id,u.user_id,u.id,u.name,m.username,m.mobile ,SUM(d.money) AS total_money  FROM tp_gambler_king AS u INNER JOIN tp_member m on u.user_id=m.id LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE $where1) AS d ON u.id=d.king_id  where $where GROUP BY u.id   ORDER BY total_money   DESC ,u.id ASC  limit $start ,$pagesize  ";

        $sql2="SELECT m.cover_id,u.user_id,u.id,u.name,m.username,m.mobile ,SUM(d.money) AS total_money  FROM tp_gambler_king AS u INNER JOIN tp_member m on u.user_id=m.id LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE $where1) AS d ON u.id=d.king_id  where $where GROUP BY u.id   ORDER BY total_money   DESC ,u.id ASC ";
        $sql3="SELECT m.cover_id,u.user_id,u.id,u.name,m.username,m.mobile ,SUM(d.money) AS total_money  FROM tp_gambler_king AS u INNER JOIN tp_member m on u.user_id=m.id LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE $where1) AS d ON u.id=d.king_id  where $where GROUP BY u.id   ORDER BY total_money   DESC ,u.id ASC  limit 3 ";
        $king_list_third=Db::query($sql3);
        $king_list=Db::query($sql2);

        $king_arr=[];
        foreach ($king_list as $k=>$v){
            $king_arr[$v['id']]=$k+1;
        }
        $total = GamblerKing::where($where3)->count();
        $list=Db::query($sql);
        $count = count($list);//总条数
        foreach ($king_list_third as $k=>$v){
            $king_list_third[$k]['image']=get_picture_url($v['cover_id']);
            $king_list_third[$k]['ranking_number']= $king_arr[$v['id']];
//            $list[$k]['profit_money']=$v->getrecharge($where);
            $king_list_third[$k]['recharge_money']=$v['total_money']+0;
        }
        foreach ($list as $k=>$v){
            $list[$k]['image']=get_picture_url($v['cover_id']);
            $list[$k]['ranking_number']= $king_arr[$v['id']];
//            $list[$k]['profit_money']=$v->getrecharge($where);
            $list[$k]['recharge_money']=$v['total_money']+0;
        }

        return ['total'=>$total,'per_page'=>$pagesize,'current_page'=>$currPage,'last_page'=>ceil($count/$pagesize),'data'=>$list,'third_list'=>$king_list_third];

//
//        $arr1=array_column($list,'achievement');
//        array_multisort($arr1,SORT_DESC,$list);

//        $list = array_slice($list,$start,$pagesize);

//        return ['total'=>$count,'per_page'=>$pagesize,'current_page'=>$page,'last_page'=>ceil($count/$pagesize),'data'=>$list];
    }



    /***
     * 分类赌王
     */

    public function  cate_king($data){
        $where=['cates'=>['like','%,'.$data['cate_id'].',%'],'status'=>1,'state'=>2];
        !empty($data['search']) && $where['name']=['like','%'.$data['search'].'%'];
        $king_list=$this->modelGamblerKing->getList($where,'id,user_id,name,sex,winning_rate,fail_rate,tags,help_number,cover_id,credit_score','profit desc');
        foreach ($king_list as $ke=>$va){
            $king_list[$ke]['image']=$va->image;
            $king_list[$ke]['investment_count']=$va->investment_count;
            $king_list[$ke]['tags_name']=$va->tags_name;


        }
        return $king_list;
    }

    /***
     * OTC排行榜
     */

    public function  otc_ranking($data){
        $where=['state'=>2];
        !empty($data['search']) && $where['shop_name']=['like','%'.$data['search'].'%'];
        $pagesize= empty($data['list_rows'])?10:$data['list_rows'];
        $currPage= empty($data['page'])?1:$data['page'];
        $list=$this->modelOtcShop->field('id,shop_name,user_id,total_count')->where($where)->order('total_count desc')->limit($pagesize)->page($currPage)->select();
        $king_list_third=$this->modelOtcShop->field('id,shop_name,user_id,total_count')->where(['state'=>2])->order('total_count desc')->limit(3)->select();
        $king_list=$this->modelOtcShop->where(['state'=>2])->order('total_count desc')->column('id');
        $total=$this->modelOtcShop->where($where)->count();
        $king_arr=[];
        foreach ($king_list as $k=>$v){
            $king_arr[$v]=$k+1;
        }
        foreach ($king_list_third as $ke=>$va){
            $king_list_third[$ke]['image']=$va->member->avtar;
            unset($va->member);
            $king_list_third[$ke]['ranking_number']= $king_arr[$va['id']];

        }
        foreach ($list as $ke=>$va){
            $list[$ke]['image']=$va->member->avtar;
            unset($va->member);
            $list[$ke]['ranking_number']= $king_arr[$va['id']];

        }
        return ['total'=>$total,'per_page'=>$pagesize,'current_page'=>$currPage,'last_page'=>ceil($total/$pagesize),'data'=>$list,'third_list'=>$king_list_third];
    }


    /***
     * 会员等级排行榜
     */
    public function  level_ranking_list(){
        $list=Member::field('cover_id,id,username,level_id,user_image')->where(['is_inside'=>0])->order('level_id desc, level_time desc')->limit(10)->select();
        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->avtar;
            $list[$k]['level_name']=$v->level->level_name;
            unset($v->level);
        }
        return $list;
    }


    /***
     * 会员排行榜
     */
    public function  recharge_ranking_list($data){
        $type=$data['user_type'];
        $where='u.status=1 and u.is_inside=0';
        $where1=' type= '.$type;
        $where3=['status'=>1,'is_inside'=>0];
        switch ($data['type']){
            case 1:
                //今天
                $date=date('Y-m-d');
                $start_time=strtotime($date.' 00:00:00');
                $end_time=strtotime($date.' 23:59:59');
                $where1.=' and d.create_time between '.$start_time.' and '.$end_time;
                break;
            case 2:
                //昨天
                $date=date('Y-m-d');
                $start_time=strtotime($date.' 00:00:00')-86400;
                $end_time=strtotime($date.' 23:59:59')-86400;
                $where1.=' and d.create_time between '.$start_time.' and '.$end_time;
                break;

                break;
            case 3:
                //  前天
                $date=date('Y-m-d');
                $start_time=strtotime($date.' 00:00:00')-86400*2;
                $end_time=strtotime($date.' 23:59:59')-86400*2;
                $where1.=' and d.create_time between '.$start_time.' and '.$end_time;
                break;


                break;
            case 4:
                //近7天
                $start_time=TIME_NOW-86400*7;
                $end_time=TIME_NOW;
                $where1.=' and d.create_time between '.$start_time.' and '.$end_time;

                break;
            case 5:

                //近15天
                $start_time=TIME_NOW-86400*15;
                $end_time=TIME_NOW;
                $where1.=' and d.create_time between '.$start_time.' and '.$end_time;

                break;
            case 6:
//              //近30天
                $start_time=TIME_NOW-86400*30;
                $end_time=TIME_NOW;
                $where1.=' and d.create_time between '.$start_time.' and '.$end_time;
                break;
        }
        if (!empty($data['start_time'])) {
            if (!empty($data['end_time'])) {
                $where1.=' and u.create_time between '.strtotime($data['start_time'] . ' 00:00:00') .' and '.strtotime($data['end_time'] . ' 23:59:59');

            } else {
                $where1.=' and u.create_time between '.strtotime($data['start_time'] . ' 00:00:00') .' and '.strtotime($data['start_time'] . ' 23:59:59');
            }
        }
        !empty($data['search']) && $where.=' and u.username like "%'.$data['search'].'%"';
        !empty($data['search']) && $where3['username']=['like','%'.$data['search'].'%'];
        $currPage=empty($data['page'])?1:$data['page'];

        $pagesize= empty($data['list_rows'])?10:$data['list_rows'];
        $start=($currPage-1)*$pagesize;

        $sql="SELECT u.cover_id,u.id,u.username,u.level_id ,SUM(d.money) AS total_money  FROM tp_member AS u LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE $where1) AS d ON u.id=d.user_id  where $where GROUP BY u.id   ORDER BY total_money   DESC ,u.id asc limit $start ,$pagesize ";

        $list=Db::query($sql);
        $sql2="SELECT u.id,u.username,u.level_id,u.cover_id ,SUM(d.money) AS total_money  FROM tp_member AS u LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE $where1) AS d ON u.id=d.user_id  where u.status=1 and u.is_inside=0 GROUP BY u.id   ORDER BY total_money   DESC ,u.id asc";

        $user_list=Db::query($sql2);
        $sql3="SELECT u.id,u.username,u.level_id,u.cover_id ,SUM(d.money) AS total_money  FROM tp_member AS u LEFT  JOIN (SELECT *FROM  tp_user_ranking_data WHERE $where1) AS d ON u.id=d.user_id  where u.status=1 and u.is_inside=0 GROUP BY u.id   ORDER BY total_money   DESC ,u.id asc  limit 3 ";
        $king_list_third=Db::query($sql3);
        $king_arr=[];
        foreach ($user_list as $k=>$v){
            $king_arr[$v['id']]=$k+1;
        }
//        dd($list);
        $total = Member::where($where3)->count();
        $count = count($list);//总条数
        foreach ($king_list_third as $k=>$v){
            $king_list_third[$k]['image']=get_picture_url($v['cover_id']);
            $king_list_third[$k]['ranking_number']=$king_arr[$v['id']];
//            $list[$k]['profit_money']=$v->getrecharge($where);
            $king_list_third[$k]['recharge_money']=$v['total_money']+0;
        }
        foreach ($list as $k=>$v){
            $list[$k]['image']=get_picture_url($v['cover_id']);
            $list[$k]['ranking_number']=$king_arr[$v['id']];
//            $list[$k]['profit_money']=$v->getrecharge($where);
            $list[$k]['recharge_money']=$v['total_money']+0;
        }


        return ['total'=>$total,'per_page'=>$pagesize,'current_page'=>$currPage,'last_page'=>ceil($count/$pagesize),'data'=>$list,'third_list'=>$king_list_third];
    }



    /***
     * 赌王动态
     */

    public function  king_action($data){
        $where=[];
        if(!empty($data['type'])){
            $where['a.type']=$data['type'];
        }
        $list_rows =  $data['list_rows'];
        $page  = $data['page'];
        
        if(!empty($data['search'])){
            $where['c.name']=['like','%'.$data['search'].'%'];
        }
        $this->modelGamblerKingAction->alias('a');

        $join = [
            [SYS_DB_PREFIX . 'gambler_king c', 'king_id = c.id'],
        ];
        $this->modelGamblerKingAction->join = $join;

        $list=$this->modelGamblerKingAction->getList($where,'a.id,a.type,a.user_investment_id,a.content,a.king_id,a.create_time,a.content_json','a.id desc');
        $count = DB::name("gambler_king_action")->alias('a')->where($where)->count();
        $last_page = (int)($count/$list_rows)+1;
        
        $time=time();
       

        
        foreach ($list as $k=>$v){
            
            $list[$k]['ranking_number']=$v->king->ranking;
            $list[$k]['action_image']=$v->image;
            $list[$k]['credit_score']=$v->king->credit_score;
            $list[$k]['tags_name']=explode(',',$v->king->tags_name);
            $list[$k]['king_name']=$v->king->getData('name');
            $list[$k]['king_image']=$v->king->user->avtar;
            $list[$k]['rand_number']='2019'.$k;
            $list[$k]['show']=0;
//            $list[$k]['addtime']=date('Y-m-d',$v['create_time']);
            $minute=floor(($time-$v['create_time'])/60);
            $hour=floor($minute/60);
            $day=floor($hour/24);
            if(floor(($time-$v['create_time']))<1){
                $list[$k]['addtime']=floor(($time-$v['create_time'])).lang('秒前');
            }elseif($minute<60){
                $list[$k]['addtime']=$minute.lang('分钟前');

            }elseif($hour<24){
                $list[$k]['addtime']=$hour.lang('小时前');

            }else{

                $list[$k]['addtime']=date('Y年m月d日 H:i:s',$v['create_time']);
            }
            
            
            $list[$k]['bonus_list']=$v->content_json;
            // $fake_data = Db::name("fake_data")->where(["king"=>$v->king->getData('name')])->select();
            // $list[$k]['fake_bonus_list']=[];
            // foreach($fake_data as $key=>$value){
            //     $fake_data[$key]['bonus'] = $value['money']*$value['percent']/100;
            //     $fake_data[$key]['draw_count'] = $value['draw_count'];
            //     $fake_data[$key]['king_bonus'] = 0;
            //     $fake_data[$key]['lose_count'] = $value['loss_count'];
            //     $fake_data[$key]['money'] = $value['money'];
            //     $fake_data[$key]['username'] = $value['user_name'];
            //     $fake_data[$key]['winn_count'] = $value['win_count'];
            // }
            // $list[$k]['fake_bonus_list'] = $fake_data;
            
            // dump($list[$k]['bonus_list']);exit;
            
           


            $list[$k]['investment_info']=[];
//            $list[$k]['king_investment_info']=[];
            if($v['type']==2){
                $investment_info=['investment_name'=>$v->kinginvestment->investment->getData('name'),'investment_cycle'=>$v->kinginvestment->investment->cycle];
                $list[$k]['investment_info']=$investment_info;
//                $list[$k]['bonus_list']=$this->modelBonusLog->alias('a')->field('a.pei_money,a.number,a.king_bonus,m.username,win_count,lose_count,flat_count')->join('__MEMBER__ m','m.id=a.user_id')->where(['a.type'=>2])->select();
                unset($v->kinginvestment);
            }
            if($v['type']==3){
                $king_investment_info=['investment_name'=>$v->kinginvestment->investment->getData('name'),'surplus_money'=>$v->kinginvestment->surplus_money,'user_count'=>$v->kinginvestment->surplus_money/$v->kinginvestment->price,'cycle'=>$v->kinginvestment->investment->cycle];
                $list[$k]['investment_info']=$king_investment_info;
                unset($v->kinginvestment);
            }
            unset($v->cate);
            unset($v->king);
        }

        if(empty($data['type']) || $data['type']==3){
            $investment_user_share_reward=getConfig('investment_user_share_reward')/100;
            $investment_king_share_reward=getConfig('investment_king_share_reward')/100;
            $list2 = Db::name("fake_data")->where("1=1")->select();
            foreach($list2 as $key=>$value){                
                $king = Db::name("gambler_king")->where(["name"=>$value['king']])->find();
               
                $investment = Db::name("gambler_king_investment")->where(['id'=>$value["product_id"]])->find();
                $ranking_number = 0;
                $list2[$key]['ranking_number']=$ranking_number;
                $list2[$key]['type']=3;
                $list2[$key]['action_image']=[];
                $list2[$key]['credit_score']=$king['credit_score'];
                
                $tags_id=explode(',',$king['tags'])[1];
                $list2[$key]['tags_name'][] = Db::name("king_category")->where(["id"=>$tags_id])->find()["name"];
                $list2[$key]['king_name']=$king['name'];
                $king_user = Db::name("member")->where(["id"=>$king['user_id']])->find();
                $list2[$key]['king_image']=get_picture_url($king_user['cover_id']);
                $list2[$key]['rand_number']='2019'.$key;
                $list2[$key]['show']=0;
                // $king_investment_info = [];
                // $king_investment_info['cycle'] = $investment['cycle'];
                // $king_investment_info['investment_name'] = $investment['name'];
                // $list2[$k]['investment_info']=$king_investment_info;
               
                $minute=floor(($time-$value['create_time'])/60);
                $hour=floor($minute/60);
                $day=floor($hour/24);
                
                if(floor(($time-$value['create_time']))<1){
                    $list2[$key]['addtime']=floor(($time-$value['create_time'])).lang('秒前');
                }elseif($minute<60){
                    $list2[$key]['addtime']=$minute.lang('分钟前');
                }elseif($hour<24){
                    $list2[$key]['addtime']=$hour.lang('小时前');
    
                }else{
    
                    $list2[$key]['addtime']=date('Y年m月d日 H:i:s',$value['create_time']);
                }
               
                $user_name = explode(',',$value['user_name']);
                $list2[$key]['bonus_list'] = [];
                foreach($user_name as $ke=>$va){
                    $fake_data['bonus'] = format_money($value['money']*$value['percent']/100*(1-$value['king_percent']/100)*(1-$investment_user_share_reward),2);
                    $fake_data['draw_count'] = $value['draw_count'];
                    $fake_data['king_bonus'] = format_money($value['money']*$value['percent']/100*$value['king_percent']/100*(1-$investment_king_share_reward),2);
                    $fake_data['lose_count'] = $value['loss_count'];
                    $fake_data['money'] = $value['money'];
                    $fake_data['username'] = $va;
                    $fake_data['winn_count'] = $value['win_count'];
                    $list2[$key]['bonus_list'][] = $fake_data;
                }; 
                
                    $investment_info = [];
                    $investment_info['investment_name'] = $investment['name'];
                    $investment_info['cycle'] = $investment['cycle'];
                    
                    $list2[$key]['investment_info']=$investment_info;
            }
            
            if($page==$last_page){
                foreach($list2 as $value2){
                    $list[]=$value2;
                }
            }
           
        }

        return $list;

    }


    /**
     * 游戏记录
     */
    public function king_games_log($data){
        $where['type']=$data['order_type'];
        switch ($data['type']){
            case 1:
                //今天

                $where['create_time']=['between',[getTodayStart(),getTodayEnd()]];
                break;
            case 2:
                //昨天
                $where['create_time']=['between',[getTodayStart()-86400,getTodayEnd()-86400]];
                break;
            case 3:
                //  前天
                $where['create_time']=['between',[getTodayStart()-86400*2,getTodayEnd()-86400*2]];

                break;
            case 4:
                //近7天
                $where['create_time']=['between',[getTodayStart()-86400*7,getTodayEnd()-86400*7]];

                break;
            case 5:

                //近15天
                $where['create_time']=['between',[getTodayStart()-86400*15,getTodayEnd()-86400*15]];

                break;
            case 6:
//              //近30天
                $where['create_time']=['between',[getTodayStart()-86400*30,getTodayEnd()-86400*30]];
                break;
        }

        if (!empty($data['start_time'])) {
            if (!empty($data['end_time'])) {
                $where['create_time']=['between',[strtotime($data['start_time'] . ' 00:00:00'),strtotime($data['end_time'] . ' 23:59:59')]];

            } else {
                $where['create_time']=['between',[strtotime($data['start_time'] . ' 00:00:00'),strtotime($data['start_time'] . ' 23:59:59')]];

            }
        }

        $list=$this->modelGamesLog->getList($where,'remark,number,state,id,create_time,order_no');
        foreach ($list as $k=>$v){
                $list[$k]['state_text']=$v->state_text;
                switch ($data['order_type']){
                    case 1:
                        $list[$k]['order_name'] ='总包转游戏';
                        break;
                    case 2:
                        $list[$k]['order_name']='游戏余额提现';
                        break;
                    case 3:
                        $list[$k]['order_name']='游戏余额划转';
                        break;
                    case 4:
                        $list[$k]['order_name']=$v->king->data['name'].'下注流水';
                        break;
                    case 5:
                        $list[$k]['order_name']=$v->king->data['name'].'赌王委托投注';
                        unset($v->king);
                        break;
                    case 6:
                        $list[$k]['order_name']='游戏返点';
                        break;

                }

        }

        return $list;



    }

    /***
     * 预测计划结果
     */

    public function forecast_result($data){
        $king=GamblerKing::get($data['id']);
        if(!$king){
            return  ajaxreturn(1,lang('您不是赌王'));
        }
        if($data['type']==1){
            //委托带单接口

            $arr['success_cycle']=$king['king_success_cycle'];
            $arr['accuracy_rate']=$king['king_accuracy_rate'];
            $arr['max_win']=$king['king_max_win'];
            $arr['current_win']=$king['king_current_win'];
            $arr['max_continuous_error']=$king['king_max_continuous_error'];
            $arr['lose_count']=$king['king_lose_count'];
            if(empty($data['lottery_id'])){
                $list=$this->modelBetsLog->getList(['king_id'=>$data['id'],'state'=>['lt',4]],'*','id desc');
            }else{
                $list=$this->modelBetsLog->getList(['king_id'=>$data['id'],'lottery_id'=>$data['lottery_id'],'state'=>['lt',4]],'*','id desc');
            }
            



        }else{
            //预测计划结果
            $member=Member::get($king['user_id']);
            $arr['success_cycle']=$member['forecast_success_cycle'];
            $arr['accuracy_rate']=$member['forecast_accuracy_rate'];
            $arr['max_win']=$member['forecast_max_win'];
            $arr['current_win']=$member['forecast_current_win'];
            $arr['max_continuous_error']=$member['forecast_max_continuous_error'];
            $arr['lose_count']=$member['forecast_lose_count'];
            $list=$this->modelBetsLogSubscribe->getList(['user_id'=>$member['id'],'lottery_id'=>$data['lottery_id']],'*','id desc');
        }
        foreach ($list as $k=>$v){
            if($v['state']==1 ){
                $list[$k]['is_winner']=3;
                $list[$k]['result']='';
            }else{
                $list[$k]['result']=LotteryResult::where(['round'=>$v['round'],'lottery_id'=>$v['lottery_id']])->value('number');
            }
            if(empty($v['is_winner']) && $v['state']>1){
                if($v['reward_money']>$v['money']){
                    $list[$k]['is_winner']=1;
                }else{
                    $list[$k]['is_winner']=2;
                }
            }
            if($data['type']==1){
                $list[$k]['investment_name']=$v->kinguser->investment->data['name'];
                unset($v->kinguser);
            }
            $list[$k]['reward_arr']=explode(',',$v['reward_arr']);
            if($v['is_old']==1){
                $list[$k]['play_name']=$v->play->playcate->data['name'].'-'.$v->play->data['name'];
            }else{
                $list[$k]['play_name']=$v->play->data['name'];
            }
        }
        $arr['list']=$list;
        return $arr;
    }


    public function  clash_data(){
        $member=$this->logicApiBase->member;
        $info['share_balance']=CompanyAccount::where(['id'=>2])->value('balance');
        $info['loss_bet']=$member['loss_bet'];
        $info['static_reward']=BonusLog::where(['type'=>2,'user_id'=>$member['id'],'number'=>['gt',0]])->sum('number')+0;
        $info['action_reward']=UserAccountLog::where(['type'=>['in',[10,11,12]],'user_id'=>$member['id']])->sum('number')+0;
        $day=date('d');
        if($day>=16){


            $info['release_1']=Db::name('dig_click')->where(['user_id'=>$member['id'],'create_time'=>['between',[strtotime(date('Y-m-16 00:00:00')),strtotime(date('Y-m-01 00:00:00', strtotime('+1 month') ))]],'status'=>1])->value('surplus_number')+0;
            $info['release_2']='';
            $info['is_dig']=Db::name('dig_click')->where(['user_id'=>$member['id'],'create_time'=>['between',[strtotime(date('Y-m-16 00:00:00')),strtotime(date('Y-m-01 00:00:00', strtotime('+1 month') ))]],'status'=>1])->count();
            $info['down_time']=  strtotime(date('Y-m-1 00:05:00',strtotime('next month')))-TIME_NOW;


        }else{

            $info['is_dig']=Db::name('dig_click')->where(['user_id'=>$member['id'],'create_time'=>['between',[strtotime(date('Y-m-01 00:00:00')),strtotime(date('Y-m-16 00:00:00'))]],'status'=>1])->count();
            $info['down_time']=  strtotime(date('Y-m-16 00:05:00'))-TIME_NOW;
            $info['release_1']='';
            $info['release_2']=Db::name('dig_click')->where(['user_id'=>$member['id'],'create_time'=>['between',[strtotime(date('Y-m-01 00:00:00')),strtotime(date('Y-m-16 00:00:00' ))]],'status'=>1])->value('surplus_number')+0;

        }




        return $info;



}

    /**
     * 点击对撞
     */
    public function clash_click()
    {
        $member=$this->logicApiBase->member;
        $day=date('d');
        if($day>=16){
            $time1=strtotime(date('Y-m-01 00:00:00'));
            $time2=strtotime(date('Y-m-15 23:59:59'));

            $info['down_time']=  strtotime(date('Y-m-1 00:05:00',strtotime('next month')))-TIME_NOW;
        }else{

            $time1=strtotime(date('Y-m-16 00:00:00', strtotime('-1 month')));
            $time2=strtotime(date('Y-m-01 00:00:00'))-1;
            $days_count=date("t");
            $info['down_time']=  strtotime(date('Y-m-'.$days_count.' 00:05:00',strtotime('next month')))-TIME_NOW;
        }

        $info['clash_entrusted_amount']=UserKingInvestment::where(['state'=>['in',[4,6,8]],'user_id'=>$member['id'],'create_time'=>['between',[$time1,$time2]]])->sum('money')+0;
        $total=0;
        $total+=Db::name('investment_bet_log')->where(['state'=>['gt',1],'user_id'=>$member['id'],'create_time'=>['between',[$time1,$time2]]])->sum('number');
        $total+=BetsLog::where(['create_time'=>['between',[$time1,$time2]],'entrust_count'=>0,'user_id'=>$member['id']])->sum('money');
        //个人下注流水
        $info['clash_business_flow']=$total;
        //个人返点
        $info['clash_return_point']=GamesLog::where(['user_id'=>$member['id'],'create_time'=>['between',[$time1,$time2]],'type'=>6])->sum('number')+0;

        //委托收益
        $info['clash_static_reward']=BonusLog::where(['type'=>2,'user_id'=>$member['id'],'number'=>['gt',0],'create_time'=>['between',[$time1,$time2]]])->sum('number')+0;
        //分享收益
        $info['clash_share_reward']=UserAccountLog::where(['type'=>10,'user_id'=>$member['id'],'create_time'=>['between',[$time1,$time2]]])->sum('number')+0;
        //团队收益
        $info['clash_team_reward']=UserAccountLog::where(['type'=>['in',[11,12]],'user_id'=>$member['id'],'create_time'=>['between',[$time1,$time2]]])->sum('number')+0;
        $uids=Member::where(['path'=>['like','%,'.$member['id'].',%']])->column('id');
        $team_profit=$team_business=0;
        if($uids){
            $team_business+=BetsLog::where(['create_time'=>['between',[$time1,$time2]],'entrust_count'=>0,'user_id'=>['in',$uids]])->sum('money')+Db::name('investment_bet_log')->where(['state'=>['gt',1],'user_id'=>['in',$uids],'create_time'=>['between',[$time1,$time2]]])->sum('number');
            $team_profit+=Db::name('investment_bet_log')->where(['state'=>['gt',1],'user_id'=>['in',$uids],'create_time'=>['between',[$time1,$time2]]])->sum('profit')+GamesLog::where(['user_id'=>['in',$uids],'create_time'=>['between',[$time1,$time2]],'type'=>4,'entrust_count'=>0])->sum('profit');
        }
        //团队盈亏
        $info['clash_team_profit']=$team_profit;
        //团队流水
        $info['clash_team_business_flow']=$team_business;
        
        if($day>=16){
            $dig_mine=Db::name('dig_click')->where(['user_id'=>$member['id'],'create_time'=>['between',[strtotime(date('Y-m-16 00:00:00')),strtotime(date('Y-m-01 00:00:00', strtotime('+1 month') ))]]])->find();
            
        }else{
            $dig_mine=Db::name('dig_click')->where(['user_id'=>$member['id'],'create_time'=>['between',[strtotime(date('Y-m-01 00:00:00')),strtotime(date('Y-m-16 00:00:00'))]]])->find();

        }
        $info['loss_bet']=$member['loss_bet'];
        
        if($dig_mine){
            $info['is_dig']=$dig_mine['status']==1?1:0;
            $info['total_dig']=$dig_mine['surplus_number'];
        }else{
            $company=CompanyAccount::get(2);
            $total=BonusLog::where(['type'=>2,'user_id'=>$member['id'],'number'=>['gt',0],'create_time'=>['between',[TIME_NOW-15*86400,TIME_NOW]]])->sum('number')+0;
            $total=$total*$member->level->lose_return/100;
            $company_account=$company['balance'];

            if ($member->loss_bet > 0) {

                if($total>0){
                    if($total>$member->loss_bet){
                        $money = 0;
                    }else{
                        $money =$member->loss_bet-$total;
                        $member->loss_bet=0;
                    }
                }else{
                    $money = $member->loss_bet;
                }

                if ($company_account == 0) {
                    //共生池余额为0，无法释放
                    $money=0;
                }

                if ($money > $company_account) {



                    $member->loss_bet += $money-$company_account;
                    $member->has_lose_bet += $company_account;
                    $money = $company_account;
                } else {
                    $member->has_lose_bet += $money;
                }

            }else{
                $money=0;
            }
            //总流水的0.001发放奖励
            $all_total = Db::name('investment_bet_log')->where(['state' => ['gt', 1], 'user_id' => $member['id'], 'create_time' => ['between', [$time1, $time2]]])->sum('number') + 0;
            $all_total += BetsLog::where(['create_time' => ['between', [$time1, $time2]], 'entrust_count' => 0, 'user_id' => $member['id'] ])->sum('money');
            if ($all_total > 0) {
                $log_money = format_money($all_total * 0.001, 2);
                if ($log_money >= 0.01 && $company->balance > 0) {
                    if ($log_money > $company->balance) {
                        $log_money = $company->balance;
                        $company->balance = 0;

                    } else {
                        $company->balance -= $log_money;

                    }
                    $money+=$log_money;

                }

            }
            $info['total_dig']=format_money($money,2);
            $member->save();
            $average_number=$info['total_dig']>1?$info['total_dig']/15:$info['total_dig'];
            $state=$info['total_dig']>0?0:1;
            Db::name('dig_click')->insert([
                'user_id'=>$member['id'],
                'create_time'=>TIME_NOW,
                'number'=> $info['total_dig'],
                'surplus_number'=>$info['total_dig'],
                'average_number'=>$average_number,
                'loss_number'=>$member->loss_bet,
                'state'=>$state
            ]);
        }





        return $info;
    }

    /***
     * 确认挖矿
     */
    public function dig_mine(){
        $member=$this->logicApiBase->member;
        $day=date('d');
        if($day>=16){
            $dig_mine=Db::name('dig_click')->where(['user_id'=>$member['id'],'create_time'=>['between',[strtotime(date('Y-m-16 00:00:00')),strtotime(date('Y-m-01 00:00:00', strtotime('+1 month') ))]]])->find();
        }else{
            $dig_mine=Db::name('dig_click')->where(['user_id'=>$member['id'],'create_time'=>['between',[strtotime(date('Y-m-01 00:00:00')),strtotime(date('Y-m-16 00:00:00'))]]])->find();

        }
        if($dig_mine['status']==1){
            return  ajaxreturn(1,lang('已经挖过，不能再次挖矿'));
        }
        Db::startTrans();
        try {

            $company=CompanyAccount::where(['id'=>2])->lock(true)->find();
            Db::name('dig_click')->update(['id'=>$dig_mine['id'],'status'=>1]);
            if($dig_mine['number']>0){
                $company->balance -= $dig_mine['number'];
                $company->save();
                //写入共生池流水
            CompanyAccountLog::create([
                'user_id'=>2,
                'type'=>4,
                'number'=>$dig_mine['number'],
                'remark'=>'对撞共生池拨出',
            ]);
            }
            Db::commit();
            return  ajaxreturn(0,lang('挖矿成功'));
        } catch (\Exception $e) {
            Db::rollback();

            return  ajaxreturn(1,$e->getMessage());
        }
    }



}
